var express = require('express');
var router = express.Router();

//数据库配置
let db = require("../model/db");

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', {
    title: 'Express'
  });
});

//规划首页接口
router.get("/index", async (req, res) => {
  let sql = `select * from stu_user`;
  let [err, data] = await db.query(sql);
  if (err) {
    res.send({
      "code": "400",
      "msg": "查询失败"
    })
  } else {
    res.send({
      "code": "200",
      "msg": "查询成功",
      data: data
    })
  }
})

//规划删除接口
router.get('/del', async (req, res) => {
  let id = req.query.id
  let sql = `delete from stu_user where id=${id} `
  let [err, data] = await db.query(sql);
  if (err) {
    res.send({
      "code": "400",
      "msg": "删除失败"
    })
  } else {
    res.send({
      "code": "200",
      "msg": "删除成功"
    })
  }
})

//规划添加接口
router.post('/add', async (req, res) => {
  console.log(req.body);
  let sql = `insert into stu_user (name,sex,age,qq) value ("${req.body.name}","${req.body.sex}",${req.body.age},"${req.body.qq}") `
  let [err, data] = await db.query(sql);
  if (err) {
    res.send({
      "code": "400",
      "msg": "添加失败"
    })
  } else {
    res.send({
      "code": "200",
      "msg": "添加成功"
    })
  }
})


// 渲染修改接口
router.get('/edit', async (req, res) => {
  let id = req.query.id
  let sql = `select * from stu_user where id=${id}`;
  let [err, data] = await db.query(sql);
  if (err) {
    res.send({
      "code": "400",
      "msg": "修改失败"
    })
  } else {
    res.send({
      "code": "200",
      "msg": "修改成功",
      data:data
    })
  }
})

// 规划修改接口
router.post('/edits',async (req,res)=>{
  let{id,name,sex,age,qq}=req.body
  let sql= `update stu_user set name="${name}",sex="${sex}",age=${age},qq="${qq}" where id=${id}`
  let [err, data] = await db.query(sql);
  if (err) {
    res.send({ "code": "400", "msg": "修改失败"})
  } else {
    res.send({ "code": "200", "msg": "修改成功"})
  }
})

module.exports = router;